//
// Created by hjie on 23-7-18.
//
#include "./../base/link.h"

void ProducerLinkList(LinkList & link_list, int number)
{
    srand(time(NULL));

    link_list.head_node = new LinkNode();
    link_list.tail_node = link_list.head_node;

    link_list.head_node->data = rand() % 50;
    link_list.head_node->next_node = nullptr;
    link_list.head_node->prev_node = nullptr;

    for (int index = 0; index < number - 1; index++)
    {
        int data = rand() % 50;
        LinkNode * node = new LinkNode();
        node->data = data;
        node->next_node = nullptr;
        node->prev_node = nullptr;

        link_list.tail_node->next_node = node;
        node->prev_node = link_list.tail_node;

        link_list.tail_node = node;
    }
    printf("producer data : ");
    LinkNode * ptr = link_list.head_node;
    while (ptr)
    {
        printf(" %d ", ptr->data);
        ptr = ptr->next_node;
    }
    printf("\n");
}


void RemoveAllEqualValue()
{
    int length = 30;
    LinkList list;
    ProducerLinkList(list, length);
    int value  = rand() % 30;

    LinkNode * ptr = list.head_node;
    LinkNode * ptr_prev = ptr;
    while (ptr)
    {
        if (ptr->data == value)
        {
            ptr_prev->next_node = ptr->next_node;
            ptr->next_node = nullptr;
            delete ptr;
            ptr = ptr_prev;
        }
        ptr_prev = ptr;
        ptr = ptr->next_node;
    }
    printf("target value : %d.\n", value);
    printf("result data  : ");
    ptr = list.head_node;
    while (ptr)
    {
        printf(" %d ", ptr->data);
        ptr = ptr->next_node;
    }
    printf("\n");
}

void RemoveRepeatNumber()
{
    int length = 12;
    LinkList list;
    SortLinkList(list, length, 5, 20);

    PrintLinkList(list);

    LinkNode * slow = list.head_node;
    LinkNode * prev = new LinkNode();
    prev->next_node = slow;
    while (slow)
    {
        LinkNode * fast = slow->next_node;
        bool has = false;
        while (fast)
        {
            if (fast->data == slow->data)
            {
                slow->next_node = fast->next_node;
                fast = slow->next_node;
                has = true;
            }
            else
            {
                break;
            }
        }
        if (has)
        {
            prev->next_node = slow->next_node;
            if (slow == list.head_node)
            {
                list.head_node = prev->next_node;
            }
            slow = prev->next_node;
        }
        else
        {
            prev = slow;
            slow = slow->next_node;
        }
    }
    printf("result data  : ");
    LinkNode * ptr = list.head_node;
    while (ptr)
    {
        printf(" %d ", ptr->data);
        ptr = ptr->next_node;
    }
    printf("\n");
}

int main(int argc, const char * argv[])
{
    //RemoveAllEqualValue();
    RemoveRepeatNumber();
    RemoveRepeatNumber();
    RemoveRepeatNumber();
    RemoveRepeatNumber();

    return 0;
}

